<template>
  <div>
    <div class="search" v-if="formColumn.length && tableConfig.search">
      <formSearch :serachConfig="tableConfig" @model="model" ref="searchRef" @query="formQuery" @reset="formQuery" :column="formColumn">
      </formSearch>
    </div>
    
    <el-card shadow="never">
      <template #header v-if="slot.middle">
        <slot name="middle"></slot>
      </template>
      <el-table 
        :row-key="rowKey"
        ref="singleTable"
        :data="props.tableData"
        stripe
        :highlight-current-row="props.radio"
        @current-change="radioChanage"
        @selection-change="selectChange"
        v-loading="props.loading"
        :default-expand-all="defaultExpandAll"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
      >
        <el-table-column fixed="left" align="center" v-if="props.check" type="selection" width="55" />
        <el-table-column
          v-for="(item,index) of tableColumn"
          :key="index"
          :align="item.align || 'center'"
          :prop="item.prop"
          :label="item.label"
          :fixed="item.fixed"
          :width="item.width"
          :min-width="item.label === 'ID' ? '50' : '120'"
          :show-overflow-tooltip="item.overflowTooltip === undefined ? true : item.overflowTooltip"
          >
          <template #default="{row,$index}">
             <!-- 在一开始时$index是-1 为了避免逻辑层出错在为-1是不渲染 -->
            <slot v-if="slot[item.prop] && $index !== -1" :index="$index" :row="row" :name="item.prop"></slot>
            <span v-else>{{ item.filterate ? item.filterate(row[item.prop],row,$index) : row[item.prop] }}</span>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagebox" v-if="props.pageConfig.pageNum">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          v-model:current-page="props.pageConfig.pageNum"
          :page-sizes="[10, 20, 50, 100]"
          v-model:page-size="props.pageConfig.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="props.pageConfig.pageTotal"
          background
          >
        </el-pagination>
      </div>
    </el-card>
  </div>
</template>

<script setup>
/**
 * 组件props和方法请查看组件描述文件
 */
import {reactive,computed,ref,useSlots } from 'vue';
import formSearch from './components/formSearch/index.vue';
import {deepClone,scrollTo} from './utils';
const slot = useSlots()
const props = defineProps({
  // 加载状态
  loading:{type:Boolean,default:false},
  // 是否可单选 ，选中项带actve样式背景
  radio:{type:Boolean,default:false},
  // 是否可多选
  check:{type:Boolean,default:false},

  defaultExpandAll:{type:Boolean,default:false},
  // 是否在组件挂在后触发 formQuery事件
  isOnmountedGet:{type:Boolean,default:true},
  // el-table :row-key="rowKey"
  rowKey:{
    type:String,
    default:'id'
  },
  // 表格数据
  tableData: {
    type: Array,
    default: () => []
  },
  // 表格列配置数组
  column: {
    type: Object || Array,
    default: () => []
  },
  // 分页配置对象
  pageConfig: {
    type: Object,
    default: () => {
      return {
        pageNum:0,
        pageSize:0,
        pageTotal:0,
      }
    }
  },
  /**表单配置项 */
  formConfig:{
    type: Object,
    default: () => ({})
  }
})
const emit = defineEmits(['pageChange','radioChange','formQuery','selectChange','model'])
const isArr = Array.isArray(props.column)
const column = isArr ? props.column : deepClone(props.column.column || [])
let tableConfig = isArr ? {} : deepClone(props.column)
delete tableConfig.column
if(tableConfig.search===undefined)tableConfig.search = true
if(tableConfig.queryBtn===undefined)tableConfig.queryBtn = true
tableConfig = Object.assign(tableConfig,props.formConfig)
const formColumn = computed(()=>{
  return column.filter(item=> item.search)
})
const tableColumn = computed(()=>{
  return column.filter(item=> item.page!==false)
})
const searchRef = ref()
function model(item,params){
  emit('model',item,params)
}
const formQuery = (params)=>{
  emit('formQuery',params,{
    ...props.pageConfig,
    pageNum:1
  })
  scrollTo(0, 800);
}
const singleTable = ref()
const params = reactive({})
const handleSizeChange = (e)=>{
  let obj = {
    ...props.pageConfig,
    pageSize:e
  }
  emit('pageChange',obj)
  emit('formQuery',searchRef.value?.getFormData(),{
    ...props.pageConfig,
  })
  scrollTo(0, 800);
}
const handleCurrentChange = (e)=>{
  let obj = {
    ...props.pageConfig,
    pageNum:e
  }
  emit('pageChange',obj)
  emit('formQuery',searchRef.value?.getFormData(),{
    ...props.pageConfig,
  })
}
const radioChanage = (row)=>{
  emit('radioChange',row || {})
}
function selectChange(rows){
  emit('selectChange',rows)
}
onMounted(()=>{
  if(props.isOnmountedGet) emit('formQuery',searchRef.value?.getFormData() || {},{...props.pageConfig})
})
defineExpose({
  // 默认选中项-多选
  addRestSelection(rows){
    if (rows) {
      rows.forEach(row => {
        singleTable.value.toggleRowSelection(row);
      });
    } else {
      singleTable.value.clearSelection();
    }
  },
  // 默认选中项-单选
  addRestradio(row){
    singleTable.value.setCurrentRow(row);
  },
  // 获取表单筛选数据
  getFormData(){
    return searchRef.value.getFormData()
  },
  // 重置筛选表单
  reset(){
    searchRef.value.reset()
  },
  // 手动触发查询事件
  query(){
    searchRef.value.query()
  },
})
</script>

<style lang="scss" scoped>
.pagebox{
    display: flex;
    justify-content: flex-end;
    padding-right: 20px;
    padding-top: 20px;
}
</style>